﻿using LuShanTea.IService;
using LuShanTea.Web.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Front.Web.App_Start
{
    public class LuShanTeaSms
    {
        private ISettingService SettingService = DependencyResolver.Current.GetService<ISettingService>();

        public LuShanTeaSms()
        {
            UserName = SettingService.GetSettingByKey("rupenguserName").Value;
            AppKey = SettingService.GetSettingByKey("rupengappKey").Value;
            TemplateId = SettingService.GetSettingByKey("rupengtemplateId").Value;
        }

        public string AppKey { get; set; }

        public string UserName { get; set; }

        public string TemplateId { get; set; }
        /// <summary>
        /// 要发送的验证码
        /// </summary>
        public string Code { get; set; }
        /// <summary>
        /// 要发送给哪个手机号
        /// </summary>
        public string PhoneNum { get; set; }


        public AjaxResult Send(string Url)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("userName=")
                .Append(UserName)
                .Append("&appKey=")
                .Append(AppKey)
                .Append("&templateId=")
                .Append(TemplateId)
                .Append("&code=")
                .Append(Code)
                .Append("&phoneNum=")
                .Append(PhoneNum);
            string postDataStr = sb.ToString();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
            writer.Write(postDataStr);
            writer.Flush();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = "UTF-8"; //默认编码  
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = reader.ReadToEnd();

            JObject obj = (JObject)JsonConvert.DeserializeObject(retString);
            //将反序列化的JSON字符串转换成对象  

            AjaxResult result = new AjaxResult();
            string code = (string)obj["code"];
            if ((string)obj["code"] == "0")
            {
                result.Status = "ok";
            }
            else
            {
                result.Status = "error";
                result.ErrorMsg = (string)obj["msg"];
            }
            return result;
        }

    }
}